<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\common\BaseController;
use App\Http\Controllers\Controller;
use App\Models\IntermediaryModel;
use App\Services\RedisFun;
use Illuminate\Http\Request;

class IntermediaryRank extends Controller
{
    /**
     * 经纪人排行榜
     */
    public function rank_list()
    {
        //查询本地数据库经纪人数据
        $brokerList = IntermediaryModel::getAllbrokerData();
        //存储经纪人排名榜的键
        $brokerKey = 'brokerList';
        //删除排名榜的所有数据
        $config=[
            'host'=>'127.0.0.1',
            'port'=>'6379',
            'auth'=>''
        ];
        $attr=[];
        $redis=new RedisFun($config,$attr);
        $redis->del($brokerKey);
        foreach ($brokerList as $k => $v) {
            $member = $v['id'].','.$v['real_name'] . ',' . $v['company']['company_name'].','.$v['avatar'];
            //存储到redis的有序集合
            $addBrokerRes = $redis->zAdd($brokerKey, $v['turnover'], $member);
            if (!$addBrokerRes) return '更新经纪人排名失败';
        }
        return '更新经纪人排名成功';
    }
    /**
     * 获取经纪人排名
     */
    public function broker_rank()
    {
        //获取排行榜从大到小排序
        $config=[
            'host'=>'127.0.0.1',
            'port'=>'6379',
            'auth'=>''
        ];
        $attr=[];
        $redis=new RedisFun($config,$attr);
        $brokerListSort = $redis->zRevRange('brokerList', 0, -1);
        $lastBrokerList = [];
        //处理数据
        foreach ($brokerListSort as $k => $v) {
            $v = explode(',', $v);
            $lastBrokerList[] = [
                'rank' => $k + 1,
                'id' => $v[0],
                'name' => $v[1],
                'company_name' => $v[2],
                'avatar'=>$v[3]
            ];
        }
        //获取公司
        return BaseController::retJson(2000,'排行信息',$lastBrokerList);
    }

    /**
     * @return mixed
     * 经纪人详情
     */
    public function broker_detail(Request $request)
    {
        $id =$request->all()['id'];
        //查询
        $brokerDetail = IntermediaryModel::getAllbrokerData($id);

        //计算房源的数量
        $brokerDetail[0]['house_num'] = count($brokerDetail[0]['house']);
       return BaseController::retJson(2000,'经纪人信息',$brokerDetail);
    }
}
